const vmHttp = weex.requireModule('vmHttp')
const baseUrl = weex.config.env.request

const generateId = (len = 36) => {
  const x = '0123456789qwertyuioplkjhgfdsazxcvbnm'
  const l = x.length

  let tmp = ''
  for (let i = 0; i < len; i++) {
    tmp += x.charAt(Math.ceil(Math.random() * 100000000) % l)
  }

  return `${+new Date()}${tmp}`
}

const imageUpload = (sts, file) => {
  return new Promise((resolve, reject) => {
    vmHttp.uploadImage(
      {
        url: `${sts.host}.aliyuncs.com/`, // 自定义图片上传地址，默认上传地址是 eros.native.js 中的 image 地址
        params: sts, // 传递的参数
        header: {}, // 自定义请求 header
        images: [file] // 图片路径
      },
      res => resolve(res),
      err => reject(err)
    )
  })
}

const objectUpload = (sts, file) => {
  return new Promise((resolve, reject) => {
    vmHttp.uploadObject(
      {
        url: `${sts.host}.aliyuncs.com/`,
        params: sts,
        header: {},
        objects: [file]
      },
      res => resolve(res),
      err => reject(err)
    )
  })
}

const postOss = ({ files = [], userDir = 'chick', type = 'image' }) => {
  return new Promise((resolve, reject) => {
    if (!files.length) {
      resolve([])
    }
    vmHttp.fetch(
      {
        method: 'POST',
        url: `${baseUrl}/auth/signature/?userDir=${userDir}`,
        data: {}
      },
      res => {
        const sts = res.data
        const imagePaths = []
        const uploadInstances = []
        for (const file of files) {
          // key
          const key = `${userDir}/${generateId(8)}${/\.[^.]+$/.exec(file) || '.jpg'}`
          // 不用阿里返回的值（也没有返回值），自己拼地址
          imagePaths.push(`${sts.host}.aliyuncs.com/${key}`)
          // upload instance
          const itemSts = { ...sts }
          itemSts.key = key
          itemSts.OSSAccessKeyId = sts.accessid
          itemSts.success_action_status = '200'
          if (type === 'image') {
            uploadInstances.push(imageUpload(itemSts, file))
          } else {
            uploadInstances.push(objectUpload(itemSts, file))
          }
        }
        Promise.all(uploadInstances)
          .then(res => {
            // 需要单独判断是否成功
            if (!res || !res.length) {
              reject()
              return
            }
            const paths = []
            for (let i = 0; i < res.length; i++) {
              const item = res[i] || {}
              if (item.status === 0) { // 即使成功也会返回data: [null]
                paths.push(imagePaths[i]) // 有可能只上传成功一部分，但只要成功一次，都算成功
              }
            }
            if (!paths.length) {
              reject()
            } else {
              resolve(paths)
            }
          })
          .catch(err => reject(err))
      },
      err => {
        reject(err)
      }
    )
  })
}

const UploadOss = Object.create(null)
UploadOss.install = Vue => {
  Vue.prototype.$oss = {
    uploadImage: ({ files = [], userDir = 'chick' }) => {
      return postOss({ files, userDir, type: 'image' })
    },
    uploadObject: ({ files = [], userDir = 'chick' }) => {
      return postOss({ files, userDir, type: 'object' })
    }
  }
}

Vue.use(UploadOss)
